package com.wxb.testinterface.controller;


import cn.hutool.http.HttpUtil;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/gaode")
public class GaodeController {

    private static String ReGeoURL = "https://restapi.amap.com/v3/geocode/regeo?";
    private static String GeoURL = "https://restapi.amap.com/v3/geocode/geo?";
    private static String KEY = "ab5cd638c80df47a581f469bab5a124d";


    @PostMapping("/address")
    public String getAddress(@RequestBody String location) {
        StringBuffer str = new StringBuffer(ReGeoURL);
        str.append(location).append("&key=").append(KEY).append("&output=json").append("&radius=1000&extensions=all");
        String addressMessage = HttpUtil.get(str.toString());
        JSONObject result = JSONObject.parseObject(addressMessage);
        String status = result.getString("status");
        if ((status.equals("1"))) {
            // 地址信息
            String code = result.getJSONObject("regeocode").getJSONObject("addressComponent").getString("towncode");
            String address=result.getJSONObject("regeocode").getString("formatted_address");
            return "地址编码： "+code+"     "+"具体地址："+address;
        }
        return null;
    }

    @PostMapping("/longandlat")
    public String getLongAndLat(@RequestBody String addressName) {
        StringBuffer str = new StringBuffer(GeoURL);
        str.append("address=").append(addressName).append("&key=").append(KEY).append("&output=json");
        String location = HttpUtil.get(str.toString());
        //把String对象反序列化为Json对象
        JSONObject result = JSONObject.parseObject(location);
        String status = result.getString("status");
        if ((status.equals("1"))) {
            // 地址信息
            JSONArray info = result.getJSONArray("geocodes");
            JSONObject geocodes=info.getJSONObject(0);
            return geocodes.getString("location");
        }
        return null;
    }




}
